"""
K线图绘制模块
负责K线图的绘制和显示
"""
from .config import config, flags
import pyqtgraph as pg
from PyQt5 import QtGui, QtCore
from typing import List, Tuple, Optional
from .config import logger

from .BaseChart import BaseChart

class CandlestickItem(pg.GraphicsObject):
    """自定义K线绘制项"""
    
    def __init__(self, data: List[Tuple[int, float, float, float, float]], 
                 candle_width: float = 0.4):
        """
        初始化K线绘制项
        
        Args:
            data: K线数据，格式为 [(索引, 开盘, 收盘, 最低, 最高), ...]
            candle_width: K线宽度
        """
        pg.GraphicsObject.__init__(self)
        self.data = data
        self.candle_width = candle_width
        self.generatePicture()

    def generatePicture(self):
        """生成K线图形"""
        self.picture = QtGui.QPicture()
        p = QtGui.QPainter(self.picture)
        
        for (t, open_price, close, low, high) in self.data:
            flag = False
            # 设置颜色
            if close > open_price:
                p.setPen(pg.mkPen(config.RISE_COLOR))  # 涨 - 红色
                # p.setBrush(pg.mkBrush(config.RISE_COLOR))
                p.setBrush(pg.mkBrush(None))  # 不填充颜色
            elif close < open_price:
                p.setPen(pg.mkPen(config.FALL_COLOR))  # 跌 - 绿色
                p.setBrush(pg.mkBrush(config.FALL_COLOR))
            else:
                p.setPen(pg.mkPen(config.DOJI_COLOR))   # 自定义一个颜色，比如灰色
                p.setBrush(pg.mkBrush(None))            # 不填充
                flag = True

            # 画实体
            rect_height = close - open_price
            rect_height = rect_height * config.CANDLESTICK_HEIGHT_FACTOR
            if abs(rect_height) < 0.01:  # 避免实体太小
                rect_height = 0.01 if rect_height >= 0 else -0.01
            if t < 10:
                logger.debug(f"t: {t}, open_price: {open_price}, close: {close}, low: {low}, high: {high} 实体高度: {rect_height}")
            
            if flag:
                p.drawLine(
                    QtCore.QPointF(t - self.candle_width, close), 
                    QtCore.QPointF(t + self.candle_width, close)
                )

            else:
                p.drawRect(QtCore.QRectF(
                    t - self.candle_width, 
                    min(open_price, close), 
                    self.candle_width * 2, 
                    abs(rect_height)
                ))
            
            # 画上下影线
            if low != high:
                p.drawLine(
                    QtCore.QPointF(t, low), 
                    QtCore.QPointF(t, high)
                )
        
        p.end()

    def paint(self, painter, option, widget):
        """绘制K线"""
        painter.drawPicture(0, 0, self.picture)

    def boundingRect(self):
        """返回边界矩形"""
        return QtCore.QRectF(self.picture.boundingRect())


class CandlestickChart(BaseChart):
    """K线图管理类"""
    
    def __init__(self, plot_widget: pg.PlotWidget):
        """
        初始化K线图
        
        Args:
            plot_widget: PyQtGraph绘图控件
        """
        # self.plot_widget = plot_widget
        if flags.ENABLE_KLINE_CHART:
            super().__init__(plot_widget)
            self.candlestick_item: Optional[CandlestickItem] = None
            self.data: Optional[List[Tuple[int, float, float, float, float]]] = None
        
        # 设置图表基本属性
        self._setup_plot()
    
    def _setup_plot(self):
        """设置图表基本属性"""
        if not flags.ENABLE_KLINE_CHART:
            return
        self.plot_widget.setTitle("K线图")
        self.plot_widget.showGrid(x=config.SHOW_GRID_X, y=config.SHOW_GRID_Y)
        self.plot_widget.vb.disableAutoRange()
    
    def update_data(self, candlestick_data: List[Tuple[int, float, float, float, float]]):
        """
        更新K线数据
        
        Args:
            candlestick_data: K线数据
        """
        if not flags.ENABLE_KLINE_CHART:
            return
        self.data = candlestick_data
        
        # 移除旧的K线项
        if self.candlestick_item is not None:
            self.plot_widget.removeItem(self.candlestick_item)
        
        # 创建新的K线项
        self.candlestick_item = CandlestickItem(candlestick_data)
        self.plot_widget.addItem(self.candlestick_item)
    
    def set_price_range(self, min_price: float, max_price: float, padding: float = 0.1):
        """
        设置价格范围
        
        Args:
            min_price: 最低价格
            max_price: 最高价格
            padding: 边距比例
        """
        if not flags.ENABLE_KLINE_CHART:
            return
        super().set_price_range(min_price, max_price, padding)
    
    def set_x_range(self, x_min: float, x_max: float):
        """
        设置X轴范围
        
        Args:
            x_min: X轴最小值
            x_max: X轴最大值
        """
        if not flags.ENABLE_KLINE_CHART:
            return
        self.plot_widget.setXRange(x_min, x_max)
    
    def set_date_ticks(self, date_ticks: List[Tuple[int, str]]):
        """
        设置X轴日期刻度
        
        Args:
            date_ticks: 日期刻度列表
        """
        if not flags.ENABLE_KLINE_CHART:
            return
        axis = self.plot_widget.getAxis('bottom')
        axis.setTicks([date_ticks])
    
    def link_x_axis(self, other_plot):
        """
        链接X轴到另一个图表
        
        Args:
            other_plot: 要链接的图表
        """
        if not flags.ENABLE_KLINE_CHART:
            return
        self.plot_widget.setXLink(other_plot)
    
    def get_plot_widget(self) -> pg.PlotWidget:
        """获取绘图控件"""
        return self.plot_widget
